package com.guan.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;


@Service
@Slf4j
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {

    public CustomGatewayFilterFactory() {
        super(CustomConfig.class);
    }


    @Override
    public GatewayFilter apply(CustomConfig config) {
        /**
         * Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
         *ServerWebExchange: HTTP请求-响应交互的契约, 提供对HTTP请求和响应的访问, 服务器端请求属性, 请求实例,响应实例等, 类似Context⻆⾊
         * GatewayFilterChain: 过滤器链
         *
         *  Mono: Reactor核⼼类, 数据流发布者, Mono最多只触发⼀个事件, 所以可以把Mono ⽤于在异步任务完成时发出通知
         *  Mono.fromRunnable: 创建⼀个包含Runnable元素的数据流
         * */return (exchange, chain) -> {
             log.info("[Pre] Filter Request, name:" + config.getName());
             return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                 log.info("[Post] Response Filter");
             }));
         };
    }


    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }


}
